package com.fenghongzhang.day007test;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


/**
 * A simple {@link Fragment} subclass.
 */
public class ThreeFragment extends Fragment {

    private TextView fgText;
    private ImageView fgImg;
    private Button fgBtn;
    private static final String TAG = "ThreeFragment";

    private int time = 5;
    private Timer timer;
    public ThreeFragment() {
    }

    //等着别人喊我开始倒计时.
    public Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //开始倒计时
            if(msg.what == 888){
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(889);
                    }
                },0,1000);
//                Log.i(TAG, "handleMessage: ----");

            }else if(msg.what == 889){
                fgText.setText("倒计时:"+time+"秒");
                time--;
                if(time <= 0){
                    //跳转
                    Intent intent = new Intent(getActivity(), Main2Activity.class);
                    startActivity(intent);
                    getActivity().finish();
                    timer.cancel();
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_three, container, false);

        fgText = (TextView) inflate.findViewById(R.id.fg_text);
        fgImg = (ImageView) inflate.findViewById(R.id.fg_img);
        fgBtn = (Button) inflate.findViewById(R.id.fg_btn);

        fgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                Intent intent = new Intent(getActivity(), Main2Activity.class);
                startActivity(intent);
            }
        });

        //定时器

        return inflate;
    }
}
